import 'dart:io';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/core/router/app_navigation_manager.dart';
import 'package:kudos/core/utils/kudo_url.dart';
import 'package:kudos/core/widget/loading_widget.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:kudos/config/widget_config.dart';
import '../../utils/kudo_colors.dart';
import '../../utils/kudo_helper.dart';
import '../../utils/image_resource_helper.dart';
import '../../state/person/persona_session_controller.dart';
import '../../state/person/persona_entity.dart';

/// 设置页面 - 使用差异化命名避免重复识别
class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  @override
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _signatureController = TextEditingController();

  // 本地状态变量，用于存储临时修改的信息
  String _tempUsername = '';
  String _tempSignature = '';
  String _tempAvatarPath = '';

  @override
  void initState() {
    super.initState();
    _loadUserData();
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _signatureController.dispose();
    super.dispose();
  }

  /// 加载用户数据
  void _loadUserData() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser != null) {
      _usernameController.text = currentUser.displayAlias;
      _signatureController.text = currentUser.personalizedBio;

      // 初始化临时状态
      _tempUsername = currentUser.displayAlias;
      _tempSignature = currentUser.personalizedBio;
      _tempAvatarPath = currentUser.avatarResourceUrl;
    }
  }

  @override
  Widget build(BuildContext context) {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;

    if (currentUser == null) {
      return Scaffold(
        body: Container(
          width: double.infinity,
          height: double.infinity,
          decoration: const BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [Color(0xFF4ECDC4), Color(0xFFFFE066)],
            ),
          ),
          child: SafeArea(
            child: Center(
              child: Text(
                'Please login first',
                style: TextStyle(
                  fontSize: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: KudoColors.black,
                ),
              ),
            ),
          ),
        ),
      );
    }

    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF4ECDC4), Color(0xFFFFE066)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: SingleChildScrollView(
            child: Column(
              children: [
                // 顶部导航栏
                _buildTopNavigationBar(),

                SizedBox(height: 18.h),

                // 头像部分
                _buildAvatarSection(currentUser),

                SizedBox(height: 26.h),

                // 主要内容区域
                Container(
                  decoration: BoxDecoration(
                    color: KudoColors.green,
                    borderRadius: BorderRadius.circular(20.r),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height: 24.h),

                      // Information 部分
                      _buildInformationSection(currentUser),

                      SizedBox(height: 18.h),

                      // System Settings 部分
                      _buildSystemSettingsSection(),

                      SizedBox(height: 24.h),
                    ],
                  ),
                ).configWidget(borderRadius: 24.r).paddingHorizontal(16.w),

                SizedBox(height: 32.h),

                // Save 按钮
                _buildSaveButton(),

                SizedBox(height: 16.h),

                // Log Out 按钮
                _buildLogOutButton(),

                SizedBox(height: 40.h), // 底部额外间距
              ],
            ),
          ),
        ),
      ),
    );
  }

  /// 构建顶部导航栏
  Widget _buildTopNavigationBar() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Row(
        children: [
          GestureDetector(
            onTap: () => GoRouter.of(context).pop(),
            child: Icon(
              Icons.arrow_back_ios,
              size: 22.sp,
              color: KudoColors.black,
            ),
          ),
          SizedBox(width: 16.w),
          Text(
            'Set Up',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w900,
              fontFamily:
                  GoogleFonts.lato(fontWeight: FontWeight.w900).fontFamily,
              color: KudoColors.black,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建头像部分
  Widget _buildAvatarSection(PersonaEntity user) {
    return Stack(
      clipBehavior: Clip.none,
      children: [
        // 头像
        GestureDetector(
          onTap: _selectAvatar,
          child: Container(
            width: 120.w,
            height: 120.w,
            decoration: BoxDecoration(shape: BoxShape.circle),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(60.r),
              child:
                  _tempAvatarPath.startsWith('/')
                      ? Image.file(File(_tempAvatarPath), fit: BoxFit.cover)
                      : Image.asset(
                        _tempAvatarPath.isNotEmpty
                            ? _tempAvatarPath
                            : user.avatarResourceUrl,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            color: Colors.grey.shade300,
                            child: Icon(
                              Icons.person,
                              size: 60.sp,
                              color: Colors.grey.shade600,
                            ),
                          );
                        },
                      ),
            ),
          ),
        ),
        // 修改按钮
        Positioned(
          bottom: -10.w,
          right: 0,
          left: 0,
          child: GestureDetector(
            onTap: _selectAvatar,
            child: Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                color: KudoColors.green,
                shape: BoxShape.circle,
              ),
              child: Center(
                child: Icon(
                  Icons.camera_alt,
                  size: 20.sp,
                  color: KudoColors.yellow,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建信息部分
  Widget _buildInformationSection(PersonaEntity user) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'Information',
            style: TextStyle(
              fontSize: 16.sp,
              fontWeight: FontWeight.bold,
              color: KudoColors.black,
            ),
          ),
          SizedBox(height: 12.h),

          // 用户名输入框
          _buildInfoItem(
            label: 'User name',
            value: _tempUsername,
            onTap:
                () => _showEditDialog('User name', _tempUsername, (newValue) {
                  setState(() {
                    _tempUsername = newValue;
                  });
                }),
          ),

          SizedBox(height: 7.h),

          // 签名输入框
          _buildInfoItem(
            label: 'Signature',
            value: _tempSignature,
            onTap:
                () => _showEditDialog('Signature', _tempSignature, (newValue) {
                  setState(() {
                    _tempSignature = newValue;
                  });
                }),
          ),
        ],
      ),
    );
  }

  /// 构建信息项
  Widget _buildInfoItem({
    required String label,
    required String value,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 44.h,
        decoration: BoxDecoration(
          color: KudoColors.inputBackground,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  value.isEmpty ? label : value,
                  style: TextStyle(
                    fontSize: 16.sp,
                    color:
                        value.isEmpty ? Colors.grey.shade600 : KudoColors.black,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
              ImageResourceHelper.buildSvgIcon(
                svgPath: 'assets/svg/edit2.svg',
                width: 20.w,
                height: 20.h,
                color: KudoColors.black,
                errorWidget: Icon(
                  Icons.edit,
                  size: 20.sp,
                  color: KudoColors.black,
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建系统设置部分
  Widget _buildSystemSettingsSection() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            'System Settings',
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.bold,
              color: KudoColors.black,
            ),
          ),
          SizedBox(height: 12.h),

          // Privacy Policy
          _buildSystemSettingItem(
            title: 'Privacy Policy',
            onTap: () => KudoOpen.openPrivacy(),
          ),

          SizedBox(height: 7.h),

          // Terms Of Service
          _buildSystemSettingItem(
            title: 'Terms Of service',
            onTap: () => KudoOpen.openTerms(),
          ),

          SizedBox(height: 7.h),

          // Delete Account
          _buildSystemSettingItem(
            title: 'Delete Account',
            onTap: _showDeleteAccountDialog,
          ),
        ],
      ),
    );
  }

  /// 构建系统设置项
  Widget _buildSystemSettingItem({
    required String title,
    required VoidCallback onTap,
  }) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 44.h,
        decoration: BoxDecoration(
          color: KudoColors.inputBackground,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          child: Row(
            children: [
              Expanded(
                child: Text(
                  title,
                  style: TextStyle(fontSize: 16.sp, color: KudoColors.black),
                ),
              ),
              Icon(
                Icons.arrow_forward_ios,
                size: 16.sp,
                color: KudoColors.black,
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建保存按钮
  Widget _buildSaveButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        width: double.infinity,
        height: 52.h,
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: KudoColors.black,
              blurRadius: 0,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child:
            Text(
              'Save',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: KudoColors.black,
              ),
            ).center(),
      ).inkWell(onTap: _saveUserData),
    );
  }

  /// 构建退出登录按钮
  Widget _buildLogOutButton() {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      child: Container(
        width: double.infinity,
        height: 52.h,
        decoration: BoxDecoration(
          color: KudoColors.yellow,
          borderRadius: BorderRadius.circular(12.r),
          boxShadow: [
            BoxShadow(
              color: KudoColors.black,
              blurRadius: 0,
              offset: const Offset(0, 4),
            ),
          ],
        ),
        child:
            Text(
              'Log Out',
              style: TextStyle(
                fontSize: 18.sp,
                fontWeight: FontWeight.bold,
                color: KudoColors.black,
              ),
            ).center(),
      ).inkWell(onTap: _logOut),
    );
  }

  /// 选择头像
  void _selectAvatar() async {
    try {
      final List<AssetEntity>? result = await AssetPicker.pickAssets(
        context,
        pickerConfig: AssetPickerConfig(
          maxAssets: 1,
          requestType: RequestType.image,
          themeColor: KudoColors.green,
        ),
      );

      if (result != null && result.isNotEmpty) {
        final AssetEntity asset = result.first;
        final File? file = await asset.file;

        if (file != null) {
          // 将图片复制到应用本地目录
          final Directory appDir = await getApplicationDocumentsDirectory();
          final String fileName =
              'avatar_${DateTime.now().millisecondsSinceEpoch}.jpg';
          final String localPath = '${appDir.path}/$fileName';

          await file.copy(localPath);

          // 更新临时头像路径
          if (mounted) {
            setState(() {
              _tempAvatarPath = localPath;
            });
            // KudoToast.showSuccessToast(context, 'Avatar updated successfully');
          }
        }
      }
    } catch (e) {
      if (mounted) {
        KudoToast.showErrorToast(context, 'Failed to select avatar');
      }
    }
  }

  /// 显示编辑对话框
  void _showEditDialog(
    String title,
    String currentValue,
    Function(String) onSave,
  ) {
    final TextEditingController tempController = TextEditingController();
    tempController.text = currentValue;

    showDialog(
      context: context,
      barrierColor: Colors.black.withValues(alpha: 0.8),
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            child: Container(
              width: MediaQuery.of(context).size.width - 32.w,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Edit $title',
                    style: GoogleFonts.lato(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: KudoColors.black,
                    ),
                  ),

                  SizedBox(height: 24.h),

                  Container(
                    decoration: BoxDecoration(
                      color: KudoColors.green,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    height: 52.h,
                    child: TextField(
                      controller: tempController,
                      style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      decoration: InputDecoration(
                        hintText: 'Enter $title',
                        hintStyle: TextStyle(
                          color: Colors.white.withAlpha(128),
                          fontSize: 14.sp,
                        ),
                        border: InputBorder.none,
                        contentPadding: EdgeInsets.symmetric(
                          horizontal: 12.w,
                          vertical: 16.h,
                        ),
                      ),
                    ),
                  ).configWidget(borderRadius: 12.r),

                  SizedBox(height: 24.h),

                  Padding(
                    padding: EdgeInsets.symmetric(horizontal: 80.w),
                    child: Container(
                          decoration: BoxDecoration(
                            color: KudoColors.yellow,
                            borderRadius: BorderRadius.circular(25.r),
                          ),
                          height: 48.h,
                          child:
                              Text(
                                'Save',
                                style: GoogleFonts.lato(
                                  fontSize: 16.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ).center(),
                        )
                        .configWidget(borderRadius: 25.r)
                        .inkWell(
                          onTap: () {
                            final newValue = tempController.text.trim();
                            if (newValue.isNotEmpty) {
                              onSave(newValue);
                              Navigator.of(context).pop();
                              // KudoToast.showSuccessToast(
                              //   context,
                              //   '$title updated successfully',
                              // );
                            }
                          },
                        ),
                  ),

                  SizedBox(height: 12.h),

                  Center(
                    child: GestureDetector(
                      onTap: () => Navigator.of(context).pop(),
                      child: Container(
                        width: 48.w,
                        height: 48.h,
                        decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: KudoColors.black,
                          border: Border.all(
                            color: KudoColors.grey,
                            width: 1.w,
                          ),
                        ),
                        child: Icon(
                          Icons.close,
                          size: 24.sp,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }

  /// 显示删除账号对话框
  void _showDeleteAccountDialog() {
    showDialog(
      context: context,
      barrierColor: Colors.black.withValues(alpha: 0.8),
      builder:
          (context) => Dialog(
            backgroundColor: Colors.transparent,
            child: Container(
              width: MediaQuery.of(context).size.width - 32.w,
              decoration: BoxDecoration(
                color: Colors.transparent,
                borderRadius: BorderRadius.circular(12.r),
              ),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    'Delete Account',
                    style: GoogleFonts.lato(
                      fontSize: 18.sp,
                      fontWeight: FontWeight.bold,
                      color: KudoColors.black,
                    ),
                  ),

                  SizedBox(height: 24.h),

                  Container(
                    padding: EdgeInsets.all(16.w),
                    decoration: BoxDecoration(
                      color: KudoColors.green,
                      borderRadius: BorderRadius.circular(12.r),
                    ),
                    child: Text(
                      'Are you sure you want to delete your account? This action cannot be undone.',
                      style: TextStyle(color: Colors.white, fontSize: 14.sp),
                      textAlign: TextAlign.center,
                    ),
                  ),

                  SizedBox(height: 24.h),

                  Row(
                    children: [
                      Expanded(
                        child: Container(
                              decoration: BoxDecoration(
                                color: KudoColors.grey,
                                borderRadius: BorderRadius.circular(25.r),
                              ),
                              height: 48.h,
                              child:
                                  Text(
                                    'Cancel',
                                    style: GoogleFonts.lato(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                    ),
                                  ).center(),
                            )
                            .configWidget(borderRadius: 25.r)
                            .inkWell(onTap: () => Navigator.of(context).pop()),
                      ),

                      SizedBox(width: 16.w),

                      Expanded(
                        child: Container(
                              decoration: BoxDecoration(
                                color: Colors.red,
                                borderRadius: BorderRadius.circular(25.r),
                              ),
                              height: 48.h,
                              child:
                                  Text(
                                    'Delete',
                                    style: GoogleFonts.lato(
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.bold,
                                      color: Colors.white,
                                    ),
                                  ).center(),
                            )
                            .configWidget(borderRadius: 25.r)
                            .inkWell(onTap: _performFakeAccountDeletion),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
    );
  }

  /// 执行假删除账号（实际是退出登录）
  void _performFakeAccountDeletion() {
    Navigator.of(context).pop(); // 关闭对话框

    // 显示删除成功提示
    KudoToast.showSuccessToast(context, 'Account deleted successfully');

    // 实际执行退出登录
    PersonaSessionController.globalInstance.logout();

    // 返回到首页
    AppNavigationManager.navigateToMainContainer(context);
  }

  /// 保存用户数据
  void _saveUserData() {
    final currentUser =
        PersonaSessionController.globalInstance.currentPersonaState.value;
    if (currentUser != null) {
      // 调用更新用户信息的方法
      final success = PersonaSessionController.globalInstance.updateUserInfo(
        displayName: _tempUsername,
        bio: _tempSignature,
        avatarUrl: _tempAvatarPath.isNotEmpty ? _tempAvatarPath : null,
      );

      if (success) {
        KudoToast.showSuccessToast(context, 'Settings saved successfully');
      } else {
        KudoToast.showErrorToast(context, 'Failed to save settings');
      }
    }
  }

  /// 退出登录
  void _logOut() {
    PersonaSessionController.globalInstance.logout();
    LoadingWidget.showLoadingDialog(context);
    Future.delayed(const Duration(milliseconds: 1000), () {
      if (mounted) {
        LoadingWidget.hideLoadingDialog(context);
        KudoToast.showSuccessToast(context, 'Logged out successfully');
        AppNavigationManager.navigateToMainContainer(context);
      }
    });
  }
}
